package freebase;

import java.io.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.*;

class MyDB {
	Connection conn;
	//Statement stmt;

	public MyDB() {
		try {
			Class.forName("com.mysql.jdbc.Driver").newInstance();

			conn = DriverManager.getConnection(
					"jdbc:mysql://pardosa06.cs.washington.edu/freebase",
					"clzhang", "wiki");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public ArrayList<Integer> selectWpidByName(String name) {
		ArrayList<Integer> res = new ArrayList<Integer>();
		try {
			Statement stmt = conn.createStatement();
			ResultSet rs = stmt
					.executeQuery("select wpid from wpid_guid_rphid_name where name='"
							+ name + "'");
			while (rs.next()) {
				String a = rs.getString("wpid");
				res.add(Integer.parseInt(a));
			}
			stmt.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return res;
	}

	public void close() {
		try {
			this.conn.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}

public class WpidMatchArticleId {

	/**
	 * @param args
	 */
	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		System.out.println("abc");
		MyDB mydb = new MyDB();
		// read rphid & title from rph's file
		BufferedReader br = new BufferedReader(new FileReader(args[0]));
		OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(
				args[1]));
		OutputStreamWriter osw2 = new OutputStreamWriter(new FileOutputStream(
				args[2]));//for not matched lines of rph 
		String line = "";
		int ln = 0;
		while ((line = br.readLine()) != null) {
			if(ln%1000==0)System.out.print(".");
			if(ln%100000==0)System.out.println();
			ln++;
			String[] abc = line.split("\t");
			Integer rphid = Integer.parseInt(abc[0]);
			String name = abc[1];
			ArrayList<Integer> wpids = mydb.selectWpidByName(name.replace("'",
					"''"));
			if (wpids.size() == 0) {
				osw2.write(rphid+"\t"+name+"\n");
			}else {
				for(int wpid: wpids){
					osw.write(rphid + "\t" + wpid + "\t" + name + "\n");
				}
			}
		}
		osw.close();
		osw2.close();
		br.close();
		mydb.close();

	}

}
